﻿CREATE PROCEDURE dbo.s_Tracker_Car_UnInstall__Cancel
	@TrackerRequestID int
AS

DECLARE @Undo TABLE(TrackerID sysname,VIN sysname,TechnicianID int,DateStamp datetime)

BEGIN TRAN

INSERT INTO @Undo
SELECT  TrackerID,VIN,TechnicianID,DateStamp
FROM (SELECT MAX(Hist_BatchHID) AS Hist_BatchHID FROM vhist_t_Tracker_Car htc
			INNER JOIN t_TrackerRequest tr ON htc.VIN = tr.VIN
      WHERE tr.ID = @TrackerRequestID) AS BID
INNER JOIN vhist_t_Tracker_Car AS htc ON BID.Hist_BatchHID = htc.Hist_BatchHID

IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

INSERT INTO t_Tracker_Car(TrackerID,VIN,TechnicianID,DateStamp)
SELECT * FROM @Undo

IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

DELETE FROM t_Technician_Tracker
WHERE TrackerID IN (SELECT TrackerID FROM @Undo)

IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

/**/DECLARE @CI int EXEC @CI = sp__Context_WorkFlow_System 1
UPDATE t_Tracker SET StatusID = dbo.TrackerStatusBack(ID)
WHERE ID IN (SELECT TrackerID FROM @Undo)
/**/IF @@ERROR = 0 COMMIT TRAN
		ELSE ROLLBACK TRAN

EXEC sp__Context @CI
